from fastapi import APIRouter, Depends, HTTPException, Request
from typing import Dict, Any
import os
import json
from .auth import get_current_active_user, User

router = APIRouter(
    prefix="/api/settings",
    tags=["系统设置"],
    responses={404: {"description": "Not found"}},
)

# 配置文件路径
SETTINGS_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "settings.json")
os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True)

# 默认设置
DEFAULT_SETTINGS = {
    "ai": {
        "provider": "zhipu",
        "api_key": "",
        "model": "glm-4",
        "temperature": 0.7
    },
    "rpa": {
        "executor_threads": 2,
        "debug_mode": False,
        "screenshot_dir": "logs/screenshots",
        "log_level": "info"
    },
    "system": {
        "theme": "light",
        "language": "zh-CN",
        "auto_update": True
    }
}

def load_settings() -> Dict[str, Any]:
    if not os.path.exists(SETTINGS_FILE):
        save_settings(DEFAULT_SETTINGS)
        return DEFAULT_SETTINGS.copy()
    
    with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_settings(settings: Dict[str, Any]) -> None:
    with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
        json.dump(settings, f, ensure_ascii=False, indent=2)

@router.get("/", response_model=Dict[str, Any])
async def get_settings(current_user: User = Depends(get_current_active_user)):
    return load_settings()

@router.put("/", response_model=Dict[str, Any])
async def update_settings(
    request: Request,
    current_user: User = Depends(get_current_active_user)
):
    data = await request.json()
    current_settings = load_settings()
    
    # 更新设置，保持嵌套结构
    for category, values in data.items():
        if category in current_settings:
            if isinstance(values, dict) and isinstance(current_settings[category], dict):
                current_settings[category].update(values)
            else:
                current_settings[category] = values
    
    save_settings(current_settings)
    return current_settings

@router.post("/reset", response_model=Dict[str, Any])
async def reset_settings(current_user: User = Depends(get_current_active_user)):
    save_settings(DEFAULT_SETTINGS)
    return DEFAULT_SETTINGS.copy()

@router.get("/ai", response_model=Dict[str, Any])
async def get_ai_settings(current_user: User = Depends(get_current_active_user)):
    settings = load_settings()
    return settings.get("ai", DEFAULT_SETTINGS["ai"])

@router.put("/ai", response_model=Dict[str, Any])
async def update_ai_settings(
    request: Request,
    current_user: User = Depends(get_current_active_user)
):
    data = await request.json()
    settings = load_settings()
    if "ai" not in settings:
        settings["ai"] = DEFAULT_SETTINGS["ai"]
    
    settings["ai"].update(data)
    save_settings(settings)
    return settings["ai"] 